#include "serverHead/threadPool.h"


void *threadFunc(void *arg){
    threadPool_t *threadPool = (threadPool_t *)arg;
    while(1){
        int netfd;
        pthread_mutex_lock(&threadPool->taskQueue.mutex);
        while(threadPool->exitFlag == 0 && threadPool->taskQueue.queueSize == 0){
            //当未收到结束命令且任务队列为0时陷入等待
            pthread_cond_wait(&threadPool->taskQueue.cond, &threadPool->taskQueue.mutex);
        }
        //当收到结束信号则退出
        if(threadPool->exitFlag != 0){
            printf("child thread is going to exit\n");
            pthread_mutex_unlock(&threadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        //正常执行
        printf("worker thread get task\n");
        netfd = threadPool->taskQueue.pFront->netfd;
        taskDeQueue(&threadPool->taskQueue);
        pthread_mutex_unlock(&threadPool->taskQueue.mutex);
        close(netfd);
    }
}

int makeWorker(threadPool_t *threadPool){
    for(int i = 0; i < threadPool->threadnum; ++i){
        pthread_create(&threadPool->tidArr[i], NULL, threadFunc, threadPool);
    }
    return 0;
}

int workerExecute(train_t* train){
    switch(train->order){
        case ORDER_CD:
            printf("cd！\n");
            break;
        case ORDER_LS:
            printf("ls!\n");
            break;
        case ORDER_PUTS:
            printf("puts\n");
            break;
        case ORDER_GETS:
            printf("gets!\n");
            break;
        case ORDER_REMOVE:
            printf("remove!\n");
            break;
        case ORDER_PWD:
            printf("pwd!\n");
            break;
        case ORDER_MKDIR:
            printf("mkdir!\n");
            break;
        case ORDER_RMDIR:
            printf("rmdir!\n");
            break;
        default:
            printf("error!\n");
    }
    return 0;
}

int shortCommandEvent(train_t* train, int netfd){
    workerExecute(train);                                             
    close(netfd);
    return 0;
}

